<?php

namespace App\Admin\Forms;

use App\Models\User;
use Dcat\Admin\Admin;
use Dcat\Admin\Models\Administrator;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Contracts\LazyRenderable;
use Illuminate\Support\Facades\DB;

class BatchReceiveUser extends Form implements LazyRenderable
{
    use LazyWidget; // 使用异步加载功能

    // 处理请求
    public function handle(array $input)
    {
        // id转化为数组
        $id = explode(',', $input['id'] ?? null);

        if (!$id) {
            return $this->response()->error('参数错误');
        }

        $user = User::find($id);


        if ($user->isEmpty()) {
            return $this->response()->error('用户不存在');
        }

        // 这里改为循环批量修改
        $user->each(function ($user) use ($input) {
            $user->update(['agent' => $input['agent'], 'agent_code' => $input['agent_code']]);
        });

        return $this->response()->success('指定成功')->refresh();
    }

    public function form()
    {
        // 获取外部传递参数
        $id = $this->payload['id'] ?? null;
        $this->text('agent_code', '认领')->required();
        $this->hidden('agent')->value(Admin::user()->id);
        // 设置隐藏表单，传递用户id
        $this->hidden('id')->attribute('id', 'reset-password-id');
    }
}
